﻿Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Reflection

Namespace SQLDataAccess

    Public Class DataRowReflectionBuilder(Of T)

        Private Shared _objDDataRowReflectionBuilders As New Dictionary(Of Type, DataRowReflectionBuilder(Of T))
        Private _objProperties As PropertyInfo()
        Private Sub New()
        End Sub

        Public Function Build(ByVal objRow As DataRow) As T

            Dim objReturnValue As T = DirectCast(Activator.CreateInstance(GetType(T)), T)

            For intX As Integer = 0 To objRow.Table.Columns.Count - 1

                If _objProperties(intX) IsNot Nothing AndAlso Not IsDBNull(objRow(intX)) Then
                    _objProperties(intX).SetValue(objReturnValue, objRow(intX), Nothing)
                End If

            Next

            Return objReturnValue
        End Function

        Public Shared Function CreateBuilder(ByVal objRow As DataRow) As DataRowReflectionBuilder(Of T)

            Dim objBuilder As DataRowReflectionBuilder(Of T) = Nothing

            If Not _objDDataRowReflectionBuilders.TryGetValue(GetType(T), objBuilder) Then
                objBuilder = New DataRowReflectionBuilder(Of T)
            End If

            objBuilder._objProperties = New PropertyInfo(objRow.Table.Columns.Count - 1) {}

            For intX As Integer = 0 To objRow.Table.Columns.Count - 1
                objBuilder._objProperties(intX) = GetType(T).GetProperty(objRow.Table.Columns.Item(intX).ColumnName)
            Next

            Return objBuilder
        End Function

    End Class

End Namespace
